package com.cxs.plan.config;


import com.cxs.plan.domain.HttpResult;
import com.cxs.plan.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.SystemException;
import org.springframework.boot.context.properties.bind.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * RestControllerAdvice，统一异常处理
 */
@Slf4j
@RestControllerAdvice
public class ExceptionHandlerConfig {

    /**
     * 业务异常处理
     *
     * @param e 业务异常
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public HttpResult exceptionHandler(BusinessException e) {
        log.error(e.getErrorMsg());
        return new HttpResult(e.getCode(), e.getErrorMsg(),null);
    }

    /**
     * 空指针异常
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public HttpResult nullExceptionHandler(NullPointerException e) {
        log.error(e.getMessage());
        return HttpResult.error("空");
    }

    @ExceptionHandler(SystemException.class)
    public HttpResult systemExceptionHandler(SystemException e) {
        log.error("出现了异常! {}", e);
        return HttpResult.error(e.getMessage());
    }
    /* 添加校验参数异常处理 */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public HttpResult MyExceptionHandle(MethodArgumentNotValidException exception) {

        BindingResult result = exception.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();

        List<FieldError> fieldErrors = result.getFieldErrors();
        fieldErrors.forEach(error -> {
            log.error("field: " + error.getField() + ", msg:" + error.getDefaultMessage());
            errorMsg.append(error.getDefaultMessage()).append("!");
        });

        return HttpResult.error(errorMsg.toString());
    }
    /* 添加校验参数异常处理 */
    @ExceptionHandler(BindException.class)
    public HttpResult bindExceptionHandler(BindException e) {
        log.error("出现了异常! {}", e);
        return HttpResult.error(e.getMessage());
    }
    /**
     * 未知异常处理
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public HttpResult exceptionHandler(Exception e) {
        // 把错误信息输入到日志中
        log.error(e.getMessage());
        return HttpResult.error(e.getMessage());
    }

}